<template>
  <div>
    <el-card :body-style="{ padding: '20px' }">
      <div>
        <el-button
          icon="plus"
          type="primary"
          plain
          style="margin-left: 10px"
          @click="addSecret"
          >新增</el-button
        >
        <el-popover v-model="deleteVisible" placement="top" width="160">
          <p>确定要删除吗？</p>
          <div style="text-align: right; margin-top: 8px">
            <el-button
              size="small"
              type="primary"
              link
              @click="deleteVisible = false"
              >取消</el-button
            >
            <el-button size="small" type="primary" @click="deleteSecrets"
              >确定</el-button
            >
          </div>
          <template #reference>
            <el-button
              icon="delete"
              type="danger"
              plain
              style="margin-left: 10px"
              :disabled="!multipleSelection.length"
              @click="deleteVisible = true"
              >删除</el-button
            >
          </template>
        </el-popover>
      </div>
      <el-divider />
      <div>
        <el-table
          v-loading="loading"
          :data="tableData"
          style="width: 100%"
          @selection-change="handleSelectionChange"
        >
          <el-table-column align="left" type="selection" width="55" />
          <el-table-column prop="name" label="名称" width="220" />
          <el-table-column prop="hostUserName" label="用户名" width="220" />
          <el-table-column
            align="center"
            prop="protocol"
            label="协议"
            width="100px"
          >
            <template #default="scope">
              <el-tag
                class="mx-1"
                :type="fitterProtocolType(scope.row.protocol)"
                effect="light"
              >
                {{ fitterProtocolLabel(scope.row.protocol) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column
            align="center"
            prop="secretType"
            label="认证类型"
            width="300"
          >
            <template #default="scope">
              {{ fitterSecretTypeLabel(scope.row.secretType) }}
            </template>
          </el-table-column>
          <el-table-column prop="content" label="备注" width="200" />
          <el-table-column align="center" label="创建时间" width="180">
            <template #default="scope">{{
              formatDate(scope.row.created_at)
            }}</template>
          </el-table-column>
          <el-table-column fixed="right" label="操作" width="200">
            <template #header>
              <el-input v-model="search" size="small" placeholder="名称/备注">
                <template #prefix>
                  <el-icon
                    style="cursor: pointer"
                    class="el-input__icon"
                    @click="initPage"
                    ><Search
                  /></el-icon>
                </template>
              </el-input>
            </template>
            <template #default="scope">
              <el-button
                link
                type="primary"
                size="small"
                @click="editSecret(scope.row)"
                >编辑</el-button
              >
              <el-popover v-model="deleteVisible" placement="top" width="160">
                <p>确定要删除吗？</p>
                <div style="text-align: right; margin-top: 8px">
                  <el-button
                    size="small"
                    type="primary"
                    link
                    @click="deleteVisible = false"
                    >取消</el-button
                  >
                  <el-button
                    size="small"
                    type="primary"
                    @click="deleteSecret(scope.row)"
                    >确定</el-button
                  >
                </div>
                <template #reference>
                  <el-button
                    link
                    type="primary"
                    size="small"
                    @click="deleteVisible = true"
                    >删除</el-button
                  >
                </template>
              </el-popover>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="gva-pagination mt-2">
        <el-pagination
          :current-page="page"
          :page-size="pageSize"
          :page-sizes="[10, 30, 50, 100]"
          :total="total"
          layout="total, sizes, prev, pager, next, jumper"
          @current-change="handleCurrentChange"
          @size-change="handleSizeChange"
        />
      </div>
    </el-card>
    <div>
      <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="30%"
        draggable
      >
        <el-form
          ref="secretForm"
          :model="form"
          :rules="rules"
          label-width="80px"
        >
          <el-form-item label="类型" prop="secretType">
            <el-radio-group v-model="form.secretType" class="ml-4">
              <el-radio :label="passwordType" size="large"
                >用户名密码认证</el-radio
              >
              <el-radio :label="privateKeyType" size="large">秘钥认证</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="名称" prop="name">
            <el-input v-model="form.name" autocomplete="off" />
          </el-form-item>
          <el-form-item label="用户" prop="hostUserName">
            <el-input
              v-model="form.hostUserName"
              autocomplete="off"
              :suffix-icon="User"
            />
          </el-form-item>
          <el-form-item
            v-if="form.secretType === 2"
            label="私钥"
            prop="privateKey"
          >
            <el-input
              v-model="form.privateKey"
              autocomplete="off"
              type="textarea"
              :rows="2"
            />
          </el-form-item>
          <el-form-item
            v-if="form.secretType === 1"
            label="密码"
            prop="hostPassword"
          >
            <el-input
              v-model="form.hostPassword"
              autocomplete="off"
              show-password
              type="password"
            />
          </el-form-item>
          <el-form-item label="协议" prop="protocol">
            <el-select v-model="form.protocol" placeholder="请选择协议">
              <el-option
                v-for="(item, index) in protocolOpt"
                :key="index"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="备注" prop="content">
            <el-input v-model="form.content" autocomplete="off" />
          </el-form-item>
        </el-form>
        <template #footer>
          <span class="dialog-footer">
            <el-button @click="dialogVisible = false">取消</el-button>
            <el-button type="primary" @click="doAddOrUpdate"> 确认 </el-button>
          </span>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup>
import { Search, User } from "@element-plus/icons-vue";
import { ref } from "vue";
import {
  PageSecret,
  DeleteSecret,
  DeleteSecrets,
  CreateSecret,
  UpdateSecret,
} from "~/api/cmdb";
import { message } from "~/utils/utils.js";
import { formatDate } from "~/utils/format";
const deleteVisible = ref(false);
const multipleSelection = ref([]);
const handleSelectionChange = (val) => {
  multipleSelection.value = val;
};
// 搜索相关
const search = ref("");

// 分页相关
const page = ref(1);
const total = ref(0);
const pageSize = ref(10);
const handleSizeChange = (val) => {
  pageSize.value = val;
  initPage();
};
const handleCurrentChange = (val) => {
  page.value = val;
  initPage();
};
// 状态tag相关
const protocolMap = {
  1: {
    type: "",
    label: "SSH",
  },
  2: {
    type: "success",
    label: "RDP",
  },
};
const fitterProtocolLabel = (dataID) => {
  return protocolMap[dataID].label;
};

const fitterProtocolType = (dataID) => {
  return protocolMap[dataID].type;
};

const secretTypeMap = {
  1: {
    label: "用户名密码认证",
  },
  2: {
    label: "秘钥认证",
  },
};
const fitterSecretTypeLabel = (dataID) => {
  return secretTypeMap[dataID].label;
};

// 页面初始化相关
const loading = ref(true);
const tableData = ref([]);
const initPage = async () => {
  const query = {
    page: page.value,
    pageSize: pageSize.value,
    keyword: search.value,
  };
  const res = await PageSecret(query);
  if (res) {
    loading.value = false;
    tableData.value = res.list;
    total.value = res.total;
    page.value = res.page;
    pageSize.value = res.pageSize;
  }
};

// 页面添加更新相关
const form = ref({
  instanceID: "",
  name: "",
  secretType: 1,
  protocol: 1,
  hostUserName: "",
  hostPassword: "",
  content: "",
  privateKey: "",
});

const protocolOpt = [
  {
    value: 1,
    label: "SSH",
  },
  {
    value: 2,
    label: "RDP",
  },
];

const mustUint = (rule, value, callback) => {
  if (!/^[0-9]*[1-9][0-9]*$/.test(value)) {
    return callback(new Error("请输入正整数"));
  }
  return callback();
};

const rules = ref({
  name: [{ required: true, message: "请输入名称", trigger: "blur" }],
  hostUserName: [{ required: true, message: "请输入用户名", trigger: "blur" }],
});

const initForm = () => {
  if (secretForm.value) {
    secretForm.value.resetFields();
  }
  form.value = {
    instanceID: "",
    name: "",
    secretType: 1,
    protocol: 1,
    hostUserName: "",
    hostPassword: "",
    content: "",
    privateKey: "",
  };
};

const secretForm = ref(null);

const dialogVisible = ref(false);
const dialogType = ref("add");
const dialogTitle = ref("");

const passwordType = 1;
const privateKeyType = 2;
// （1） 添加认证信息
const addSecret = () => {
  initForm();
  dialogVisible.value = true;
  dialogTitle.value = "新增认证信息";
  dialogType.value = "add";
};
// （2） 编辑认证信息
const editSecret = (row) => {
  dialogVisible.value = true;
  dialogTitle.value = "编辑认证信息";
  dialogType.value = "edit";
  for (const key in form.value) {
    form.value[key] = row[key];
  }
};
// (3) 真正执行添加或编辑动作
const doAddOrUpdate = () => {
  secretForm.value.validate(async (valid) => {
    if (valid) {
      switch (dialogType.value) {
        case "add":
          const addRes = await CreateSecret(form.value);
          if (addRes) {
            dialogVisible.value = false;
            initPage();
            message(addRes);
          }
          break;
        case "edit":
          console.log("edit", form.value);
          const editRes = await UpdateSecret(form.value);
          if (editRes) {
            initPage();
            dialogVisible.value = false;
            message(editRes);
          }
          break;
      }
    }
  });
};

// 页面删除相关

// (1) 批量删除
const deleteSecrets = async () => {
  const ids = [];
  multipleSelection.value &&
    multipleSelection.value.forEach((item) => {
      ids.push(item.instanceID);
    });
  const res = await DeleteSecrets({ ids });
  if (res) {
    message(res);
    if (tableData.value.length === ids.length && page.value > 1) {
      page.value--;
    }
    deleteVisible.value = false;
    initPage();
  }
};

// (2) 单条删除
const deleteSecret = async (row) => {
  const res = await DeleteSecret(row.instanceID);
  if (res) {
    message(res);
    initPage();
  }
};

// 实际调用
initPage();
</script>

<style></style>
